<template>
	<div v-loading="loading" class="home-view">
		<div class="map" :id="mapId"></div>

		<LegendCom v-if="showLegend" :right="20" :top="680" :width="500" :data="data" @showAll="showAll" @closeAll="closeAll"></LegendCom>
	</div>
</template>

<script lang='ts' setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import API from '../api/home';
import CFG from '@/utils/config';
import dayjs from 'dayjs';

const loading = ref(false);
const mapId = ref('homeMap');
const newlayerId = ref('tianjinLayer');
const route = useRoute();
const width = ref(500);
// const homeLineLayer = ref();

const oldEle = ref('');

onMounted(() => {
	initMap();
});

watch(() => route.query, (newQuery, oldQuery) => {
	console.log('watch route======>', newQuery.element, oldQuery.element);
	oldEle.value = oldQuery.element as string;
	clearAllLayers();
	if (newQuery.element) {
		let eleArr: string[] = (newQuery.element as string).split(',');
		if (eleArr.length > 1) {
			let countArr: string[] = (newQuery.count as string).split(',');
			let heightArr: string[] = (newQuery.height as string).split(',');
			if (countArr[0] > countArr[1]) {
				eleArr.reverse();
				heightArr.reverse();
			}
			eleArr.forEach((el: string, index: number) => {
				selectProductMakeByte(newQuery.type as string, el, heightArr[index]);
			});
			
		} else {
			selectProductMakeByte(newQuery.type as string, '', '');
		}
	}
}, {
	deep: true
});

const setTianJinArea = () => {
	let option = [
		{
			rings: (window as any).mapObj[mapId.value].geometryData.areaconfig['12'].rings,
			style: {
				strokeStyle: "#18e6fa", //边框颜色#18e6fa
				lineWidth: 0, //边框宽度
				fillStyle: 'rgba(0,0,0,0)' //填充色
			}
		}
	];
	(window as any).GIS.Graphic.showPolygon(
		mapId.value,
		newlayerId.value,
		option,
		{ zIndex: 10 }
	);
};

const initMap = () => {
	(window as any).GIS.Init.initMap(
		mapId.value,
		'tianjin',
		'tianjin_WGS84',
		() => {
			(window as any).GLMap.setLevel(6);
			setTianJinArea();
			route.query.element && selectProductMakeByte(route.query.type as string, '', '');
		},
		[114.94, 38.32, 119.80, 40.47],
		'main',
		{fileName: 'regionData.json'}
	);
};

const ysqProductMakeByte = async () => {
	try {
		// clearAllLayers();
		loading.value = true;
		let res = await API.ysqProductMakeByte({
			time: route.query.time,
			period: route.query.period,
			element: route.query.element,
			cluster: route.query.cluster,
		});
		if (res.data.byteLength > 0) {
			console.log('resParseRaw======>', (window as any).G.ParseRaw(res.data));
			if (route.query.element === 'gh500_cluster') {
				createIsoline(res.data);
			} else {
				showGridRectify(res.data, '');
			}
		} else {
			ElMessage.error('当前时间暂无数据');
		}
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
}

const showGridRectify = (res: any, el: string) => {
	let { element } = route.query;
	let typeArr = [];
	if (el) element = el;
	if (element === 'eda2') {
		typeArr = [
			{ type: 'wind', visible: true, id: 'windId' },
		]
	} else {
		typeArr = [
			{ type: 'splash', visible: true, id: 'splashId', uv: false, wd: true, cacheConfig: 'noCache'},
			{ type: 'number', visible: true, id: 'numberId', uv: false, wd: true, cacheConfig: 'noCache'},
		]
		if (element === 'eda10') {
			typeArr.push({ type: 'wind', visible: true, id: 'windId', uv: true, wd: false, cacheConfig: 'noCache'});
		}
	}
	(window as any).GIS.GridShow.showByTypes_raw(
		mapId.value,
		typeArr,
		res,
		{},
		{
			imageData: imageData.value,
			levels: levels.value,
			// disInter: false,
			// areaCode: 'h9_boundary',
			// cutFlag: true,
			// isCut: true,
			decimals: 1
		},
		4326
	);

	// (window as any).GIS.GridShow.showGrid_rectify(
	//   mapId.value,
	//   [{ type: 'splash', visible: true, id: 'splashId' }],
	//   res,
	//   {},
	//   {
	//     imageData,
	//     disInter: false,
	//     // areaCode: 'h9_boundary',
	//     cutFlag: true,
	//     levels
	//   },
	//   4326
	// );
};

const createIsoline = (res: any) => {
	let rawInfo = (window as any).G.ParseRaw(res);
	let rangeObj = (window as any).G.ParseRaw(res).rangeObj;
	let dval = 0.2;
	// let levels: number[] = [400, 404, 408, 412, 416, 420, 424, 428, 432, 436, 440, 444, 448, 452, 456, 460, 464, 468, 472, 476, 480, 484, 488, 492, 496, 500, 504, 508, 512, 516, 520, 524, 528, 532, 536, 540, 544, 548, 552, 556, 560, 564, 568, 572, 576, 580, 584, 588, 592, 596];
	let levels: number[] = [];
	let ele = route.query.element as string;
	let height = route.query.height as string;
	if (['gh'].includes(ele)) ele = `${ele}_${height}`; //ECJH-高度
	if (Object.keys(CFG).includes(ele)) {
		levels = (CFG as any)[ele].levels;
	}

	let cutRings = [[
		[rangeObj.xmin + dval, rangeObj.ymax - dval],
		[rangeObj.xmax - dval, rangeObj.ymax - dval],
		[rangeObj.xmax - dval, rangeObj.ymin + dval],
		[rangeObj.xmin + dval, rangeObj.ymin + dval],
		[rangeObj.xmin + dval, rangeObj.ymax - dval]
	]];

	let row = rawInfo.rangeObj.nRows;
	let coloum = rawInfo.rangeObj.nCols;
	let zvalues = rawInfo.data; //格点值数组(从左上角开始的一维数组)
	let matrix = (window as any).NinePointsSmoothing.prototype.transformToMatrix(zvalues, row, coloum);
	matrix = (window as any).NinePointsSmoothing.prototype.smoothWithTimes(matrix, row, coloum, null, null, 10);
	zvalues = (window as any).NinePointsSmoothing.prototype.transformToValues(matrix, row, coloum);

	let geoExtent = [rawInfo.rangeObj.xmin, rawInfo.rangeObj.ymin, rawInfo.rangeObj.xmax, rawInfo.rangeObj.ymax]; //格网对应的地理范围
	let symbol = new (window as any).G.GLPolylineSymbol(1, "rgba(0,0,0,1)", 1, 1, 0); //默认等值线样式
	let labelOptions = {
		fillStyle: "rgba(255,0,0,1)", //标注颜色
		font: "14px 微软雅黑", //标注字体
		gap: 400, //标注间隙
		textWidthRatio: 0.4, //当标注字体长度与线条长度占比大于该值时，绘制标注
		// rangeObj: {
		// 	lineCut: true,
		// 	cutRings: cutRings || [[[]]]  //裁剪范围
		// }
	};

	//创建等值线图层
	let homeLineLayer = (window as any).GIS.Layer.IsolineLayerHelper.createIsolineLayer(
		(window as any).GLMap, 
		'homeLineLayer', 
		zvalues, 
		row, 
		coloum, 
		levels, 
		geoExtent, 
		symbol, 
		labelOptions, 
		3, 
		null, 
		null, 
		true
	);
	//把等值线图层添加到map中
	(window as any).GLMap.addLayer(homeLineLayer);
}

const queryData = async (type: string, el: string, h: string) => {
	let { queryTime, element, period, height, handleType = '2' } = route.query;
	try {
		if (el) element = el;
		if (h) height = h;
		// if (!['eda', 'eda2'].includes(element as string)) {
		// 	clearAllLayers();
		// }
		// clearAllLayers();
		loading.value = true;
		let params = {
			queryTime: queryTime, //起报时间（北京时）,格式:yyyyMMddHHmmss，08时或20时
			element: element === 'eda2' ? 'eda' : element,
			period: period, //时效,ECC6F是15~46，ECJH是000~360（前150隔3，后面隔6）
			height: height //高度层 hPa（10.0 50.0 100.0 200.0 300.0 400.0 500.0 700.0 850.0 925.0 1000.0 ），ECJH类型RH要素需要传
		}
		if (type === 'queryECE6FData') {
			params.type = handleType;
		}
		let res = await (API as any)[type](params);
		if (res.data.byteLength > 0) {
			console.log('resParseRaw======>', (window as any).G.ParseRaw(res.data));
			let ele = element as string;
			if (['msl', 'gh'].includes(ele)) {
				createIsoline(res.data);
			} else {
				showGridRectify(res.data, el);
			}
		} else {
			ElMessage.error('当前时间暂无数据');
		}
	} catch (error) {
		console.error(error);
	} finally {
		loading.value = false;
	}
}

const showLegend = ref(false);
const imageData = ref<number[]>([]);
const levels = ref<number[]>([]);
const data = ref<any[]>([]);

const selectProductMakeByte = (type: string, el: string, h: string) => {
	let { element, height, queryTime, currentTime } = route.query;
	let ele = element as string;
	if (el) ele = el;
	if (h) height = h;
	
	if (['tmp', 'eda', 'eda2', 'q', 'w', 'rh'].includes(ele)) ele = `${ele}_${height}`; //ECJH-高度
	showLegend.value = false;
	if (!['msl', 'gh'].includes(ele)) {
		if (Object.keys(CFG).includes(ele)) {
			let legendTitle = `${type}_${(CFG as any)[ele].legendTitle}_${dayjs(String(queryTime), 'YYYYMMDDHHmmss').format('MM-DD HH:mm')}/${dayjs(String(currentTime), 'YYYY-MM-DD HH:mm').format('MM-DD HH:mm')}`;
			let legendOptions = (CFG as any)[ele].legendOptions;
			imageData.value = (CFG as any)[ele].imageData;
			levels.value = (CFG as any)[ele].levels;
			data.value = [
				{title: legendTitle, options: legendOptions, disabled: false, show: true}
			];
			showLegend.value = true;
		}
	}

	if (type === 'extendedForecast') { //延伸预报
		type = '延伸预报';
		ysqProductMakeByte();
	} else {
		queryData(type === 'ecjh' ? 'queryEcjhData' : type === 'ecc6f' ? 'queryECC6FData' : 'queryECE6FData', el, h);
	}
};

const clearAllLayers = () => {
	showLegend.value = false;
	(window as any).mapObj[mapId.value].layerIds.includes('splashId') && (window as any).GIS.LayerControll.deleteLayer(mapId.value, ['splashId']);
	(window as any).mapObj[mapId.value].layerIds.includes('numberId') && (window as any).GIS.LayerControll.deleteLayer(mapId.value, ['numberId']);
	(window as any).mapObj[mapId.value].layerIds.includes('windId') && (window as any).GIS.LayerControll.deleteLayer(mapId.value, ['windId']);
	(window as any).mapObj[mapId.value].layerIds.includes('homeLineLayer') && (window as any).GIS.LayerControll.deleteLayer(mapId.value, ['homeLineLayer']);
	// homeLineLayer.value && (window as any).G.GLMap.removeLayer(homeLineLayer.value);
}

const showAll = (data: boolean) => {
	if (data) {
		(window as any).GIS.LayerControll.showControll(mapId.value, ['splashId', 'numberId'], true);
	} else {
		(window as any).GIS.LayerControll.showControll(mapId.value, ['splashId', 'numberId'], false);
	}
}

const closeAll = () => {
	clearAllLayers();
	showLegend.value = false;
}
</script>

<style lang='scss' scoped>
.home-view {
	height: 100%;
	width: 100%;

	.map {
		height: 100%;
		width: 100%;
	}
}
</style>